package com.beadwallet.alarm.base.datasource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 *
 * @author master
 * @date 2017/1/18
 */
@Configuration
@EnableTransactionManagement
public class DataSourceConfiguration {

    private static final Logger log = LoggerFactory.getLogger(DataSourceConfiguration.class);

    @Value("${dataSource.type}")
    private Class<? extends DataSource> dataSourceType;

    @Bean(name = "dataSource0")
    @Primary
    @ConfigurationProperties(prefix = "dataSource.dataSource0")
    public DataSource dataSource0() {
        log.info("------------ dataSource0---database--init -------------");
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

    /***
     * 将所有数据源 放到 Map集合中
     * @return
     */
    @Bean("chooseDataSource")
    public ChooseDataSource getAllDataSource() {
        ChooseDataSource dataSource = new ChooseDataSource();
        HashMap<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("dataSource0", dataSource0());
        dataSource.setTargetDataSources(dataSourceMap);
        dataSource.setDefaultTargetDataSource(dataSource0());
        return dataSource;
    }

}
